const Tag = require("../models/Tag");

// 标签控制器
async function createTag(req, res) {
    try{
        const {name} = req.body
        const oldTag = await Tag.findOne({
            where:{
                name
            }
        })


        if(oldTag){
            if(!oldTag.isDeleted){
                return res.json({msg:"标签已存在"})
            }

            oldTag.isDeleted = false
            const newDate = +new Date()
            oldTag.createAt = newDate
            oldTag.updateAt = newDate
            
            await oldTag.save()
            return res.json(oldTag)
        }


        // 之前没创建过标签则直接船舰
        const newTag = await Tag.create({name})
        res.json(newTag)

    }catch(error){
        res.status(500).json({error:error.message})
    }
}

async function getTags(req, res) {
    try{
        const tags = await Tag.findAll({
            where:{isDeleted:false},
            attributes:{exclude:['isDeleted']}
        })
        res.json(tags)
    }catch(error){
        res.status(500).json({error:error.message})
    }
}

async function updateTag(req, res) {
    // todo
}

async function deleteTag(req, res) {
    try {
      const { id } = req.params;
      const tag = await Tag.findByPk(id);
      if (!tag) {
        return res.status(404).json({ error: "Tag not found" });
      }
      tag.isDeleted = true;
      await tag.save();
      res.json({ status: "OK" });
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }
  

module.exports = { createTag, getTags, updateTag, deleteTag };
